package com.atmilan.quartz.service.impl;

import com.atmilan.quartz.constant.Constants;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.SyncStatusEnum;
import com.atmilan.quartz.model.dto.coltorti.ColtortiProductResDTO;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.dto.hiqer.HiQErProductDTO;
import com.atmilan.quartz.model.dto.hiqer.HiQErProductResDTO;
import com.atmilan.quartz.model.dto.im.ImProductResDTO;
import com.atmilan.quartz.model.entity.coltorti.ColtortiProduct;
import com.atmilan.quartz.model.entity.crmeb.StoreProduct;
import com.atmilan.quartz.model.entity.crmeb.SystemConfig;
import com.atmilan.quartz.model.entity.hiqer.HiQErProduct;
import com.atmilan.quartz.service.*;
import com.atmilan.quartz.utils.RedisUtil;
import com.atmilan.quartz.utils.product.ColtortiProductUtil;
import com.atmilan.quartz.utils.product.HiQErProductUtil;
import com.atmilan.quartz.utils.source.SourceColtortiProductUtil;
import com.atmilan.quartz.utils.source.SourceHiQErProductUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Howe Hsiang
 */
@Slf4j
@Service
public class HiQErSyncServiceImpl implements IHiQErSyncService {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ISystemConfigService systemConfigService;
    @Autowired
    IHiQErProductService hiQErProductService;

    @Autowired
    IHiQErProductSkuService hiQErProductSkuService;

    @Autowired
    IStoreProductService storeProductService;
    @Autowired
    IStoreProductAttrService storeProductAttrService;
    @Autowired
    IStoreProductAttrValueService storeProductAttrValueService;
    @Autowired
    SourceHiQErProductUtil sourceHiQErProductUtil;
    @Autowired
    ColtortiProductUtil coltortiProductUtil;

    @Autowired
    HiQErProductUtil hiQErProductUtil;

    /**
     * 获取远程数据并保存到数据源
     */
    @Override
    public Boolean syncProduct() {
        // 数据清空
        hiQErProductService.deleteAll();
        hiQErProductSkuService.deleteAll();

        //获取普通商品
        int pageNo = 1;
        int pageSize = 50;
        int pageCount = 1;
        long millis = System.currentTimeMillis();
        while(pageNo <= pageCount) {
            try {

                HiQErProductResDTO hiQErProductResDTO = hiQErProductUtil.selectHiQerPage(pageNo,pageSize,1);

                if(!hiQErProductResDTO.getSuccess()) {
                    log.info("--------------- hiqer获取商品接口请求失败 {}---------------",hiQErProductResDTO.getMessage());
                    return false;
                }

                List<HiQErProduct> hiqerProducts = hiQErProductResDTO.getData();

                if(CollectionUtils.isEmpty(hiqerProducts)) {
                    return true;
                }
                
                // 商品保存
                saveGoods(hiqerProducts,1);

                Integer total = hiQErProductResDTO.getTotal();
                pageCount = (total + pageSize - 1) / pageSize;

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            log.info("--------------- hiqer远程抓取数据, 第: {} 页,  总共: {} 页, 总耗时: {} 分  ---------------", pageNo, pageCount, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
            pageNo++;
        }

        //获取跨境商品
        int pageNoKj = 1;
        int pageSizeKj = 50;
        int pageCountKj = 1;
        long millisKj = System.currentTimeMillis();
        while(pageNoKj <= pageCountKj) {
            try {

                HiQErProductResDTO hiQErProductResDTO = hiQErProductUtil.selectHiQerPage(pageNoKj,pageSizeKj,2);

                if(!hiQErProductResDTO.getSuccess()) {
                    log.info("--------------- hiqer获取跨境商品接口请求失败 {}---------------",hiQErProductResDTO.getMessage());
                    return false;
                }

                List<HiQErProduct> hiqerProducts = hiQErProductResDTO.getData();

                if(CollectionUtils.isEmpty(hiqerProducts)) {
                    return true;
                }

                // 商品保存
                saveGoods(hiqerProducts,2);

                Integer totalKj = hiQErProductResDTO.getTotal();
                pageCountKj = (totalKj + pageSizeKj - 1) / pageSizeKj;

            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }

            log.info("--------------- hiqer远程抓取数据, 第: {} 页,  总共: {} 页, 总耗时: {} 分  ---------------", pageNoKj, pageCountKj, (int)((System.currentTimeMillis() - millisKj) / 1000 / 60));
            pageNoKj++;
        }

        return true;
    }
    
    // 商品源数据保存
    private void saveGoods(List<HiQErProduct> goodsList,Integer is_cross_border) {
        // 商品数据
        List<HiQErProduct> goodsEntity = new ArrayList<>();
        for(HiQErProduct goods : goodsList) {
            HiQErProduct productEntity = new HiQErProduct();
            BeanUtils.copyProperties(goods, productEntity);
            productEntity.setIsCrossBorder(is_cross_border);
            productEntity.setCreateTime(new Date());
            goodsEntity.add(productEntity);

        }

        hiQErProductService.saveBatch(goodsEntity);
    }

    @Override
    public Boolean pushProduct() {
        try {
            // 当次更新少于5千条, 则不更新, 并且重新拉取
            int count = hiQErProductService.count();
            if(5000 > count) {
                systemConfigService.update(Wrappers.<SystemConfig>lambdaUpdate()
                        .eq(SystemConfig :: getName, Constants.COLTORTI_SYNC_STATUS)
                        .set(SystemConfig :: getFormId, SyncStatusEnum.PUSH)
                        .set(SystemConfig :: getUpdateTime, new Date())
                        );
                log.info("--------------- hiqer商品源数据, 少于规定条数, 不进行下发, 总条数为: {} ---------------", count);
                return false;
            }

            // 将所有hiqer商品更新状态置为未更新
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct :: getIsEurope, ProductTypeEnum.HIQER.getCode())
                    .set(StoreProduct :: getUpdateFlag, false)
                    );

            // 商品更新操作
            int pageNo = 1;
            int pageSize = 100;
            int maxPage = (count + pageSize - 1) / pageSize;
            log.info("--------------- 开始分页查询hiqer商品源数据, 本次更新总条数为: {} ---------------", count);

            long millis = System.currentTimeMillis();
            while (pageNo <= maxPage) {
                try {
                    PageHelper.startPage(pageNo, pageSize);
                    List<HiQErProduct> hiQErProducts = hiQErProductService.list();
                    PageInfo<HiQErProduct> pageInfo = PageInfo.of(hiQErProducts);
                    List<HiQErProduct> products = pageInfo.getList();
                    buildProduct(products);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                log.info("--------------- hiqer下发商品到数据库, 当前页数: {}, 总页数: {}, 耗时: {} 分 ---------------", pageNo, maxPage, (int)((System.currentTimeMillis() - millis) / 1000 / 60));
                pageNo++;
            }
            // 图搜删除
            storeProductService.delSeachImage(ProductTypeEnum.HIQER);
            // 查询是否异常下放(新更新商品数量小于500)
            int newCount = storeProductService.count(Wrappers.<StoreProduct>lambdaQuery()
            		.eq(StoreProduct::getIsEurope, ProductTypeEnum.HIQER.getCode())
            		.eq(StoreProduct::getUpdateFlag, true)
            		.eq(StoreProduct :: getIsShow, true)
            		);
            if(500 > newCount) {
            	log.info("--------------- hiqer下发商品异常, {} 数量不对!!!! ---------------", newCount);
                return true;
            }
            // 下架所有未更新数据
            storeProductService.update(Wrappers.<StoreProduct>lambdaUpdate()
                    .eq(StoreProduct::getIsEurope, ProductTypeEnum.HIQER.getCode())
                    .eq(StoreProduct::getUpdateFlag, false)
                    .eq(StoreProduct :: getIsShow, true)
                    .eq(StoreProduct :: getIsDel, false)
                    .set(StoreProduct::getIsShow, false)
                    .set(StoreProduct::getStock, 0)
                    .set(StoreProduct::getLastPushTime, new Date())
                    .set(StoreProduct::getIsTusou, false)
                    );
            // 下架所有sku库存
            storeProductService.downloadSku(ProductTypeEnum.HIQER.getCode());

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 商品构建处理
     * @Description:  
     * @author daigb 
     * @param @param products
     * @return void
     * @throws
     */
    private void buildProduct(List<HiQErProduct> products) {
        try {
            for (HiQErProduct product : products) {

                int stock = product.getStock();
                if (0 >= stock) {
                    continue;
                }

                // 构建实体
                StoreProductCrmebRequest storeProductCrmebRequest = sourceHiQErProductUtil.buildColtortiProduct(product);
                if(null == storeProductCrmebRequest) {
                	log.info("--------------- hiqer下发异常, 商品无数据 !---------------");
                    continue;
                }
                // 数据保存
                StoreProduct storeProduct = storeProductService.getByBarCode(storeProductCrmebRequest.getBarCode(), storeProductCrmebRequest.getSuppliersId(), storeProductCrmebRequest.getKeyword());
                storeProductService.saveOtProduct(storeProductCrmebRequest, storeProduct, stock);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
}
